import apiConfig from './apiConfig'
import axios from '../axios/index'
import instance from '../axios/instance'
import store from "../vuex";

// 获取接口配置数据
// {{ api }} 接口在apiConfig中的位置 -链接

function apiGetPosition(api) {
    let apiPosition = api.split('-')
    let position = null
    apiPosition.forEach(item => {
        if (position) {
            position = position[item]
        } else {
            position = apiConfig[item]
        }
    })
    return position
}



// apiCall方法返回axios结果类 可直接放入axios提供的同步方法中
// {{prama}} api 接口在apiConfig中的位置  多级使用 - 分隔 （ customer-listData ）
// {{prama}} data 接口接收的参数  如果data类型是FormData 会使用instance上传操作
// {{prama}} type 调用类型 axios通用 all同步处理 download下载
// {{prama}} method 请求类型

function apiCall(prama) {
    let api = prama.api,
        param = prama.data ? prama.data : {},
        type = prama.type,
        onUploadProgress = prama.onUploadProgress

    let position = apiGetPosition(api)
    let method = position.method || 'post'

    if (type == 'all') {

        return axios({
            method: method,
            url: position.url,
            data: param
        })

    } else if (Object.prototype.toString.call(prama.data) == '[object FormData]') {//数据判断类型为FormData

        store.commit('setLoading')
        return new Promise(function (resolve, reject) {
            instance.post(
                position.url,
                prama.data,
                {
                    'authorization': sessionStorage.getItem('token') || '',
                    'Content-Type': 'multipart/form-data;boundary=----' + new Date().getTime(),
                    onUploadProgress
                }
            ).then(res => {
                store.commit('closeLoading')
                resolve(res)
            }).catch(err => {
                store.commit('closeLoading')
                store.commit('setAlert', {
                    show: true,
                    massage: err,
                    type: 'error',
                    time: 2,
                })
                reject(err)
            })
        });

    } else if (type == 'download') {

        store.commit('setLoading')
        return new Promise(function (resolve, reject) {
            axios({
                method: method,
                url: position.url,
                responseType: 'arraybuffer',
                data: param
            }).then(res => {
                store.commit('closeLoading')
                resolve(res)
            }).catch(err => {
                store.commit('closeLoading')
                store.commit('setAlert', {
                    show: true,
                    massage: err,
                    type: 'error',
                    time: 2,
                })
                reject(err)
            })
        });

    } else {
        store.commit('setLoading')
        return new Promise(function (resolve, reject) {
            axios({
                method: method,
                url: position.url,
                data: param
            }).then(res => {
                store.commit('closeLoading')
                resolve(res)
            }).catch(err => {
                store.commit('closeLoading')
                store.commit('setAlert', {
                    show: true,
                    massage: err,
                    type: 'error',
                    time: 2,
                })
                reject(err)
            })
        });
    }

}


// apiSynchronization方法同步调用接口
// {{ prama }} apiOrderList api接口配置 数组 单项参数参照apiCall
// 内部循环调用了apiCall方法

function apiSynchronization(apiOrderList) {

    let orderList = []

    apiOrderList.forEach(item => {
        orderList.push(apiCall({
            api: item.api,
            method: item.method,
            data: item.data,
            type: 'all'
        }))
    })

    store.commit('setLoading')

    return new Promise(function (resolve, reject) {
        axios.all(orderList).then(resList => {

            resList.forEach( (res, index) => {
                if (apiOrderList[index].callBack) {
                    apiOrderList[index].callBack(res)
                }
            })
            resolve(resList)
            store.commit('closeLoading')

        }).catch(err => {
            openTip(err)
            reject(err)
            store.commit('closeLoading')

        })
    });


}



// network报错顶部弹出异常提示  只在测试与开发环境下生效
function openTip(err) {
    if (process.env.VUE_APP_CURRENTMODE == 'test' || process.env.NODE_ENV == 'development') {
        if (!err.response) {
            store.commit('setTopError', {
                show: true,
                msg: err
            })
        } else {
            store.commit('setTopError', {
                show: true,
                msg: `CODE: ${err.response.status};<br/>
                URL: ${err.response.config.baseURL + err.response.config.url};<br/>
                DATA: ${err.response.config.data}`
            })
        }
    }
}




export default {
    apiCall,
    apiSynchronization
}
